//
//  HEOrderListViewController.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/11/4.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HEOrderListViewController.h"
#import "HEMyOrderCell.h"
#import "HEMyOrderFooterCell.h"
#import "HEMyOrderHeadCell.h"
#import "HEOrderDetailsViewController.h"
#import "HEOrderCommentViewController.h"
#import "HELogisticsViewController.h"

@interface HEOrderListViewController ()<UITableViewDelegate, UITableViewDataSource, HEMyOrderFooterCellDelegate, HEMyOrderHeadCellDelegate>

@property (nonatomic, strong) GDTableView *tableView;
@property (nonatomic, strong) NSMutableArray <HEOrderModel *> * dataSourceArr;

@property (nonatomic, assign) NSInteger pageNum;
@property (nonatomic, assign) NSInteger pageSize;

@end

@implementation HEOrderListViewController

- (NSMutableArray<HEOrderModel *> *)dataSourceArr {
    if (!_dataSourceArr) {
        _dataSourceArr = [NSMutableArray array];
    }
    return _dataSourceArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.zx_navBar.hidden = YES;
    self.view.backgroundColor = CViewBgColor;

    _pageNum = 1;
    _pageSize = 10;
    
    HEEmptyDataModel *empt = [HEEmptyDataModel new];
    empt.tipsImageName = @"no_order";
    [self customEmptyModel:empt];
    [self setCustomTableView:self.tableView];
    [self showEmpty];
 
    [self loadData];
}

- (GDTableView *)tableView {
    if (!_tableView) {
        _tableView = [[GDTableView alloc] initWithFrame:CGRectMake(0, 1 , KScreenWidth, KScreenHeight - ZXNavBarHeight - 47) style:UITableViewStyleGrouped];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.scrollsToTop = YES;
        _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 0.01)];
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 0.01)];

        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.backgroundColor = CViewBgColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;

        __weak __typeof(&*self)weakSelf = self;
        self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{

            weakSelf.isFromHeadRefresh = YES;
            weakSelf.pageNum = 1;
            [weakSelf loadData];
        }];

        self.tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
            weakSelf.isFromHeadRefresh = NO;
            weakSelf.pageNum += 1;
            [weakSelf loadData];
        }];

        [_tableView registerClass:[HEMyOrderCell class] forCellReuseIdentifier: KHEMyOrderCell];
        [_tableView registerClass:[HEMyOrderHeadCell class] forCellReuseIdentifier: @"HEMyOrderHeadCell"];
        [_tableView registerClass:[HEMyOrderFooterCell class] forCellReuseIdentifier: @"HEMyOrderFooterCell"];

    }
    return _tableView;
}



#pragma mark -

- (void)loadData {

    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:[NSNumber numberWithInteger:_pageNum] forKey:@"pageNum"];
    [params setValue:[NSNumber numberWithInteger:_pageSize] forKey:@"pageSize"];
    [params setValue:_status forKey:@"status"];

    [WOAFNetWorkingHandle GETWithBaseUrl:KServerUrl suffixUrl:KorderList parameters:params success:^(id  _Nonnull responseObject) {
        NSLog(@"response：  %@", [responseObject mj_JSONString]);

        if (self.isFromHeadRefresh) {
            [self.dataSourceArr removeAllObjects];
        }

        HEMallPageResponse *response = [HEMallPageResponse mj_objectWithKeyValues:responseObject];

        [self.dataSourceArr addObjectsFromArray:[HEOrderModel mj_objectArrayWithKeyValuesArray:response.data.records]];
        [self.tableView reloadData];

        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];

        if (self.dataSourceArr.count == 0) {
            [self showEmpty];
        }else {
            if (response.data.records.count == 0) {
                [Dialog toastBottom:@"没有更多数据了~"];
            }
        }

    } failure:^(NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _dataSourceArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    HEOrderModel *model = _dataSourceArr[section];
    return model.orderItemList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HEMyOrderCell *cell = [_tableView dequeueReusableCellWithIdentifier: KHEMyOrderCell];
    HEOrderModel *model = _dataSourceArr[indexPath.section];
    cell.model = model.orderItemList[indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    HEOrderModel *model = _dataSourceArr[indexPath.section];
    
    return [tableView fd_heightForCellWithIdentifier: KHEMyOrderCell cacheByIndexPath:indexPath configuration:^(HEMyOrderCell *cell) {
        cell.model = model.orderItemList[indexPath.row];
        
    }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    HEOrderModel *model = _dataSourceArr[indexPath.section];
    [self jumpToDetails:model];
}

- (void)jumpToDetails:(HEOrderModel *)model {
    HEOrderDetailsViewController *vc = [HEOrderDetailsViewController new];
    vc.orderId = model.id;
    [vc vcBackBlock:^{
        [self.tableView.mj_header beginRefreshing];
    }];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark -

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 70;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 80;
}

// tableView的sectionHeader加载数据
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    HEOrderModel *model = _dataSourceArr[section];
    HEMyOrderHeadCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HEMyOrderHeadCell"];
    cell.model = model;
    cell.statusLb.text = model.KstatusName;
    cell.statusLb.textColor = model.KstatusColor;
    cell.orderSnLb.text = [NSString stringWithFormat:@"订单号: %@", model.orderSn];
    cell.delegate = self;
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    HEOrderModel *model = _dataSourceArr[section];
    HEMyOrderFooterCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HEMyOrderFooterCell"];
    cell.model = model;
    cell.delegate = self;
    return cell;
}

#pragma mark - HEMyOrderFooterCellDelegate
- (void)bottomOperationWithModel:(HEOrderModel *)model type:(HEOrderBottomBtnType)type {
    switch (type) {
        case HEOrderBottomBtnTypeCheckDetails:
        {
            [self jumpToDetails:model];
        }
            break;
            
        case HEOrderBottomBtnTypeCancelOrder:
        {
            [WOAlert alertShowTitle:@"" message:@"您确定要取消该订单吗？" cancelButtonTitle:@"取消" otherButtonTitles:@"确定" block:^(NSInteger buttonIndex) {
                if (buttonIndex == 1) {
                    [self cancelOrder:model.id];
                }
            }];
        }
            break;
            
        case HEOrderBottomBtnTypeDelete:
        {
            [WOAlert alertShowTitle:@"" message:@"您确定要删除该订单吗？" cancelButtonTitle:@"取消" otherButtonTitles:@"确定" block:^(NSInteger buttonIndex) {
                if (buttonIndex == 1) {
                    [self deleteOrder:model.id];
                }
            }];
        }
            break;
        case HEOrderBottomBtnTypeComment:
        {
            HEOrderCommentViewController *vc = [HEOrderCommentViewController new];
            vc.model = model;
            [vc vcBackBlock:^{
                [self.tableView.mj_header beginRefreshing];
            }];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case HEOrderBottomBtnTypeChecklogistics:
        {
            HELogisticsViewController *vc = [HELogisticsViewController new];
            vc.order = model;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case HEOrderBottomBtnTypeConfirmGoods:
        {
            [WOAlert alertShowTitle:@"" message:@"您确定收货吗？" cancelButtonTitle:@"取消" otherButtonTitles:@"确定" block:^(NSInteger buttonIndex) {
                if (buttonIndex == 1) {
                    [self confimDelivery:model.id];
                }
            }];
        }
            break;
            
        default:
            break;
    }
}

/** 删除订单*/
- (void)cancelOrder:(NSInteger)orderId {
    
    [WOAFNetWorkingHandle POSTWithBaseUrlByKeyValue:KServerUrl suffixUrl:KcloseOrder parameters:@{@"orderId" : [NSNumber numberWithInteger:orderId]} success:^(id  _Nonnull responseObject) {
        NSLog(@"response：  %@", [responseObject mj_JSONString]);
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        if (response.success) {
            [Dialog toastBottom:@"订单取消成功~"];
            [self.tableView.mj_header beginRefreshing];
        }
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

/** 删除订单*/
- (void)deleteOrder:(NSInteger)orderId {
    
    [WOAFNetWorkingHandle POSTWithBaseUrlByKeyValue:KServerUrl suffixUrl:KdeleteOrder parameters:@{@"orderId" : [NSNumber numberWithInteger:orderId]} success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        if (response.success) {
            [Dialog toastBottom:@"订单删除成功~"];
            [self.tableView.mj_header beginRefreshing];
        }
    } failure:^(NSError * _Nonnull error) {
    }];
}

/** 确定收货*/
- (void)confimDelivery:(NSInteger)orderId {
    
    [WOAFNetWorkingHandle POSTWithBaseUrlByKeyValue:KServerUrl suffixUrl:KconfimDelivery parameters:@{@"id" : [NSNumber numberWithInteger:orderId]} success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        if (response.success) {
            [Dialog toastBottom:@"确认收货成功~"];
            [self.tableView.mj_header beginRefreshing];
        }
    } failure:^(NSError * _Nonnull error) {
    }];
}

#pragma mark -
- (void)footerSelect:(HEOrderModel *)model {
    [self jumpToDetails:model];
}

- (void)headSelect:(HEOrderModel *)model {
    [self jumpToDetails:model];
}

@end
